//
//  RestaurantTableViewController.swift
//  FoodPin
//
//  Created by 王巍 on 16/5/4.
//  Copyright © 2016年 ww. All rights reserved.
//

import UIKit
import CoreData

class RestaurantTableViewController: UITableViewController, NSFetchedResultsControllerDelegate, UISearchResultsUpdating {
    
    var restaurants:[Restaurant] = []
    var sr:[Restaurant] = []
    
    var frc: NSFetchedResultsController!
    
    // 搜索控制器
    var sc: UISearchController!
    
    func searchFilter(textToSearch: String){
        sr = restaurants.filter({ (r) -> Bool in
            return r.name.containsString(textToSearch)
        })
    }
    
    // 搜索框发生改变
    func updateSearchResultsForSearchController(searchController: UISearchController) {
        if var textToSearch = sc.searchBar.text {
            // 去除字符串中空格
            textToSearch = textToSearch.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
            searchFilter(textToSearch)
            tableView.reloadData()
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 初始搜索控制器 （nil搜索结果与搜索框在同一页面）
        sc = UISearchController(searchResultsController: nil)
        tableView.tableHeaderView = sc.searchBar

        sc.searchResultsUpdater = self
        // 点击搜索框时 背景不变暗
        sc.dimsBackgroundDuringPresentation = false
        
        sc.searchBar.placeholder = "输入餐馆名搜索"
        // 前景色
        // sc.searchBar.tintColor = UIColor.whiteColor()
        // 背景色
        // sc.searchBar.barTintColor = UIColor.orangeColor()
        // 设置搜索框样式
        sc.searchBar.searchBarStyle = .Minimal
        
        // 设置导航条返回按钮样式 
        navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .Plain, target: nil, action: nil)
        
        let request = NSFetchRequest(entityName: "Restaurant")
        request.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)]
        let buffer = (UIApplication.sharedApplication().delegate as? AppDelegate)?.managedObjectContext
        frc = NSFetchedResultsController(fetchRequest: request, managedObjectContext: buffer!, sectionNameKeyPath: nil, cacheName: nil)
        frc.delegate = self
        do{
            try frc.performFetch()
            restaurants = frc.fetchedObjects as! [Restaurant]
        }catch{
            print(error)
        }
    }
    
    
    override func viewDidAppear(animated: Bool) {
        
        super.viewDidAppear(animated)
        
        let defaults = NSUserDefaults.standardUserDefaults()
        if defaults.boolForKey("guiderShowed"){
            return
        }
        
        if let guidesVC = storyboard?.instantiateViewControllerWithIdentifier("guideController") as? GuidePageViewController{
            
            presentViewController(guidesVC, animated: true, completion: nil)

        }
    }
    
    func controllerWillChangeContent(controller: NSFetchedResultsController) {
        tableView.beginUpdates()
    }
    
    func controllerDidChangeContent(controller: NSFetchedResultsController) {
        tableView.endUpdates()
    }
    
    func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {
        switch type {
        case .Insert:
            if let _newindexPath = newIndexPath{
                tableView.insertRowsAtIndexPaths([_newindexPath], withRowAnimation: .Automatic)
            }
        case .Delete:
            if let _indexPath = indexPath{
                tableView.deleteRowsAtIndexPaths([_indexPath], withRowAnimation: .Automatic)
            }
            
        case .Update:
            if let _indexPath = indexPath{
                tableView.reloadRowsAtIndexPaths([_indexPath], withRowAnimation: .Automatic)
            }
            
        default:
            tableView.reloadData()
        }
        
        restaurants = controller.fetchedObjects as! [Restaurant]
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return sc.active ? sr.count : restaurants.count
    }

    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! CustomTableViewCell
        
        let r = sc.active ? sr[indexPath.row] : restaurants[indexPath.row]
        
        cell.rtImage.image = UIImage(data: r.image!)
        cell.rtName.text = r.name
        cell.rtAddr.text = r.location
        cell.rtType.text = r.type
        
        // 设置图片圆角
        cell.rtImage.layer.cornerRadius = cell.rtImage.frame.size.width / 2
        cell.rtImage.clipsToBounds = true
        
        /*
        if marked[indexPath.row] == true {
            cell.accessoryType = .Checkmark
        } else {
            cell.accessoryType = .None
        }
        */
        // cell.accessoryType = marked[indexPath.row] ? .Checkmark : .None
        cell.heartImg.hidden = !restaurants[indexPath.row].isVisited.boolValue
        
//        cell.textLabel?.text = restaurants[indexPath.row]
//        cell.imageView?.image = UIImage(named: restaurants_image[indexPath.row])

        return cell
    }
    
    /*
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        let alert = UIAlertController(title: "亲，您选择了我", message: "消息", preferredStyle: UIAlertControllerStyle.ActionSheet)
        let cancelAction = UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel, handler: nil)
        
        
        let dialHandler = { (action: UIAlertAction) -> Void in
            let alert = UIAlertController(title: "提示", message: "您拔打的电话号码暂无法接通", preferredStyle: .Alert)
            let action = UIAlertAction(title: "ok", style: .Default, handler: nil)
            alert.addAction(action)
            self.presentViewController(alert, animated: true, completion: nil)
        }
        
        let dialAction = UIAlertAction(title: "拔打 021-6543\(indexPath.row)", style: UIAlertActionStyle.Default, handler: dialHandler)
        
        let comAction = UIAlertAction(title: "我来过", style: .Default) { (action: UIAlertAction) in
            let cell = tableView.cellForRowAtIndexPath(indexPath) as! CustomTableViewCell
            //cell?.accessoryType = UITableViewCellAccessoryType.Checkmark
            cell.heartImg.hidden = false;
            self.marked[indexPath.row] = true;
        }
        
        alert.addAction(cancelAction)
        alert.addAction(dialAction)
        alert.addAction(comAction)
        
        self.presentViewController(alert, animated: true, completion: nil)
    }
    */
    
    
    // Override to support conditional editing of the table view.
    override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {

        return !sc.active
    }
    

    
    override func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? {
        let share = UITableViewRowAction(style: .Default, title: "分享") { (action, indexPath) -> Void in
            let alert = UIAlertController(title: "分享到", message: "请选择分享到的社交类型", preferredStyle: .ActionSheet)
            
            let qqAction = UIAlertAction(title: "qq", style: .Default, handler: nil)
            let wbAction = UIAlertAction(title: "微博", style: .Default, handler: nil)
            let wxAction = UIAlertAction(title: "微信", style: .Default, handler: nil)
            
            alert.addAction(qqAction)
            alert.addAction(wbAction)
            alert.addAction(wxAction)
            
            self.presentViewController(alert, animated: true, completion: nil)
        }
        // 设置按钮颜色
        // share.backgroundColor = UIColor.greenColor()
        share.backgroundColor = UIColor(red: 218/255, green: 225/255, blue: 218/255, alpha: 1)
        
        let del = UITableViewRowAction(style: .Default, title: "删除") { (action, indexPath) in
            
            
            let buffer = (UIApplication.sharedApplication().delegate as? AppDelegate)?.managedObjectContext
            let restaurantToDel = self.frc.objectAtIndexPath(indexPath) as! Restaurant
            buffer?.deleteObject(restaurantToDel)
            
            do{
                try buffer?.save()
            }catch{
                print(error)
            }
            
//            self.restaurants.removeAtIndex(indexPath.row)
//            
//            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        }
        return [share, del]
    }
    
    // Override to support editing the table view.
    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == .Delete {
            restaurants.removeAtIndex(indexPath.row)
            
            print(restaurants.count)
            
            // tableView.reloadData()
            // Delete the row from the data source
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        } else if editingStyle == .Insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    
    // 转场数据传递
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        
        if segue.identifier == "showRestaurantDetail" {
            let destVC = segue.destinationViewController as! DetailTableViewController
            destVC.hidesBottomBarWhenPushed = true
            destVC.restaurant = sc.active ? sr[tableView.indexPathForSelectedRow!.row] :
                restaurants[tableView.indexPathForSelectedRow!.row]
            
        }
    }
    

    /*
    // Override to support rearranging the table view.
    override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        return true
    }
    */

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

    
    @IBAction func unwindToHome(segue: UIStoryboardSegue){
        
    }
    
}
